package com.yanchangapp.ui.activity._n_manage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanchangapp.R;
import com.yanchangapp.adapter._n_manage.DailyPlanListAdapter;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.model.bean.DailyPlanBean;
import com.yanchangapp.model.bean.TimeBean;
import com.yanchangapp.ui.presenter.HistoryPlanAtPresenter;
import com.yanchangapp.ui.view.HistoryPlanAtView;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.time.TimeUtil;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.widget.YCLoadingView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * page: 历史计划
 *
 * todo 设置选中某一天
 */
public class HistoryPlanActivity extends BaseActivity<HistoryPlanAtView, HistoryPlanAtPresenter> implements HistoryPlanAtView, CalendarView.OnCalendarSelectListener, CalendarView.OnYearChangeListener, CalendarView.OnCalendarRangeSelectListener, CalendarView.OnMonthChangeListener {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.ibAddMenu)
    ImageButton ibAddMenu;
    RelativeLayout rlTool;
    @BindView(R.id.calendarView)
    CalendarView calendarView;
    @BindView(R.id.calendarLayout)
    CalendarLayout calendarLayout;
    @BindView(R.id.rvPlanItem)
    RecyclerView rvPlanItem;
    @BindView(R.id.tvDes)
    TextView tvDes;
    @BindView(R.id.llEmptyMsg)
    LinearLayout llEmptyMsg;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.ycLoading)
    YCLoadingView ycLoading;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.next)
    TextView tvNext;
    @BindView(R.id.arrow)
    ImageView arrow;
    @BindView(R.id.tvLeftMonth)
    TextView tvLeftMonth;
    @BindView(R.id.tvLeftYear)
    TextView tvLeftYear;
    @BindView(R.id.tvLeftLunar)
    TextView tvLeftLunar;
    @BindView(R.id.rlMin)
    RelativeLayout rlMin;
    @BindView(R.id.tvRightMonth)
    TextView tvRightMonth;
    @BindView(R.id.tvRightYear)
    TextView tvRightYear;
    @BindView(R.id.tvRightLunar)
    TextView tvRightLunar;
    @BindView(R.id.rlMax)
    RelativeLayout rlMax;
    @BindView(R.id.frameLayout)
    NestedScrollView frameLayout;
    @BindView(R.id.tvCurrMonth)
    TextView tvCurrMonth;
    private View noMoreData;
    // 昨天时间 / 过去2年时间 / 当前选中的时间
    private TimeBean todayTimeBean, lastTwoYear, currentDay;
    private DailyPlanListAdapter mDailyPlanListAdapter;
    private List<DailyPlanBean> mDailyPlanBeans = new ArrayList<>();
    private int mYear;
    private boolean isExpand = false;
    private String startTime = null;
    private String endTime = null;

    private List<Calendar> mSelectCalendars = new ArrayList<>();

    public static void show(Activity activity) {
        Intent intent = new Intent(activity, HistoryPlanActivity.class);
        activity.startActivity(intent);
    }

    private void setLoadingState(LoadingType loadingType) {
        switch (loadingType) {
            case LOADING:
                if (ycLoading.getVisibility() == View.GONE) {
                    ycLoading.setVisibility(View.VISIBLE);
                }

                if (llEmptyMsg.getVisibility() == View.VISIBLE) {
                    llEmptyMsg.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE) {
                    llErrorNetwork.setVisibility(View.GONE);
                }

                break;
            case EMPTY:
                if (ycLoading.getVisibility() == View.VISIBLE) {
                    ycLoading.setVisibility(View.GONE);
                }

                if (llEmptyMsg.getVisibility() == View.GONE) {
                    llEmptyMsg.setVisibility(View.VISIBLE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE) {
                    llErrorNetwork.setVisibility(View.GONE);
                }

                break;
            case SUCCESS:
                if (ycLoading.getVisibility() == View.VISIBLE) {
                    ycLoading.setVisibility(View.GONE);
                }

                if (llEmptyMsg.getVisibility() == View.VISIBLE) {
                    llEmptyMsg.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE) {
                    llErrorNetwork.setVisibility(View.GONE);
                }

                break;
            case ERROR:
                if (ycLoading.getVisibility() == View.VISIBLE) {
                    ycLoading.setVisibility(View.GONE);
                }

                if (llEmptyMsg.getVisibility() == View.VISIBLE) {
                    llEmptyMsg.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.GONE) {
                    llErrorNetwork.setVisibility(View.VISIBLE);
                }

                break;
        }
    }


    @Override
    protected void init() {

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_history_plan;
    }

    @Override
    protected HistoryPlanAtPresenter createPresenter() {
        return new HistoryPlanAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("历史计划");
        tvDes.setText("暂无历史计划");
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableRefresh(true);
        // 设置时间范围
        initTodayTime();
        initLastTwoYear();
        initAdapter();
        // 设置日期选择的时间范围

        calendarView.setRange(lastTwoYear.year, lastTwoYear.month, lastTwoYear.day,
                todayTimeBean.year, todayTimeBean.month, todayTimeBean.day);
        // 滑动到当前日历....
        calendarView.scrollToCurrent();
        initCurrentData();
        noMoreData = LayoutInflater.from(this).inflate(R.layout.item_no_more_data,null);
    }


    /**
     * 设置adapter...
     */
    private void initAdapter() {
        rvPlanItem.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this, 0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        rvPlanItem.setLayoutManager(manager);
        rvPlanItem.setHasFixedSize(true);
        rvPlanItem.setNestedScrollingEnabled(false);
        mDailyPlanListAdapter = new DailyPlanListAdapter(mDailyPlanBeans);
        rvPlanItem.setAdapter(mDailyPlanListAdapter);
    }

    private void initLastTwoYear() {
        java.util.Calendar todayCalendar = java.util.Calendar.getInstance();
        todayCalendar.add(java.util.Calendar.YEAR, -2);
        lastTwoYear = new TimeBean();
        lastTwoYear.year = todayCalendar.get(java.util.Calendar.YEAR);
        lastTwoYear.month = todayCalendar.get(java.util.Calendar.MONTH) + 1;
        lastTwoYear.day = todayCalendar.get(java.util.Calendar.DAY_OF_MONTH);
    }

    private void initTodayTime() {
        java.util.Calendar todayCalendar = java.util.Calendar.getInstance();
        todayTimeBean = new TimeBean();
        todayTimeBean.year = todayCalendar.get(java.util.Calendar.YEAR);
        todayTimeBean.month = todayCalendar.get(java.util.Calendar.MONTH) + 1;
        todayTimeBean.day = todayCalendar.get(java.util.Calendar.DAY_OF_MONTH);

        currentDay = new TimeBean();
        currentDay.year = todayTimeBean.year;
        currentDay.month = todayTimeBean.month;
        currentDay.day = todayTimeBean.day;


//        calendarView.setSelectStartCalendar(todayTimeBean.year,todayTimeBean.month,todayTimeBean.day);
//        tvLeftMonth.setText(todayTimeBean.month + "月" +todayTimeBean.day + "日");
//        tvLeftYear.setText(todayTimeBean.year+"");
//        tvLeftLunar.setText("今天");
//        tvNext.setVisibility(View.GONE);
//        rlMax.setVisibility(View.GONE);

        tvCurrMonth.setText(todayTimeBean.year+"."+todayTimeBean.month);
    }

    private void initCurrentData() {
//        tvYear.setText(String.valueOf(todayTimeBean.year));
//        mYear = calendarView.getCurYear();
//        tvMonthDay.setText(todayTimeBean.month + "月" + todayTimeBean.day + "日");
//        tvLunar.setText("今天");
//        tvCurrentDay.setText(String.valueOf(TimeUtil.getYesterDayOfMonth()));
    }

    @Override
    protected void initData() {
        setLoadingState(LoadingType.LOADING);
        queryHistory();
    }

    @Override
    protected void initListener() {
        ivToolbarNavigation.setOnClickListener(v -> finish());

        mDailyPlanListAdapter.setOnItemClickListener((adapter, view, position) -> PlanDetailActivity.show(HistoryPlanActivity.this, mDailyPlanBeans.get(position).getId(), false));

        calendarView.setOnCalendarSelectListener(this);
        calendarView.setOnYearChangeListener(this);
        calendarView.setOnMonthChangeListener(this);
        calendarView.setOnCalendarRangeSelectListener(this);

        // 设置点击事件之后进行数据信息的填充等...

        btnNextRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryHistory();
            }
        });

        calendarView.setOnViewChangeListener(new CalendarView.OnViewChangeListener() {
            @Override
            public void onViewChange(boolean isMonthView) {
                // 如果月视图展示
                isExpand = isMonthView;
                if (isExpand) {
                    arrow.setImageDrawable(ResHelper.getDrawable(R.drawable.icon_up));
                } else {
                    arrow.setImageDrawable(ResHelper.getDrawable(R.drawable.icon_down));
                }
            }
        });

        arrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isExpand) {
                    calendarLayout.shrink();
                } else {
                    calendarLayout.expand();
                }
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.queryHistoryPlan(startTime,endTime);
            }
        });

    }

    private void queryHistory(){
        mPresenter.queryHistoryPlan(startTime,endTime);
    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
//        tvLunar.setVisibility(View.VISIBLE);
//        tvYear.setVisibility(View.VISIBLE);
//        tvMonthDay.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
//        tvYear.setText(String.valueOf(calendar.getYear()));
//        tvLunar.setText(calendar.getLunar());

//        mYear = calendar.getYear();
//
//        // 记录年月日信息...
//        currentDay.year = calendar.getYear();
//        currentDay.month = calendar.getMonth();
//        currentDay.day = calendar.getDay();
//        // 此处进行网络请求
//        setLoadingState(LoadingType.LOADING);
//        mPresenter.queryHistoryPlan(currentDay.year + "-" + TimeUtil.fixTime(currentDay.month) + "-" + TimeUtil.fixTime(currentDay.day) + " 00:00:00");
    }

    @Override
    public void onYearChange(int year) {
        // tvMonthDay.setText(String.valueOf(year));
    }

    @Override
    public void queryHistoryList(List<DailyPlanBean> mList) {
        setLoadingState(LoadingType.SUCCESS);
        //刷新结束
        refreshLayout.finishRefresh();
        mDailyPlanBeans.clear();
        mDailyPlanBeans.addAll(mList);
        mDailyPlanListAdapter.notifyDataSetChanged();
        if (mDailyPlanBeans.size() == 0) {
            setLoadingState(LoadingType.EMPTY);
            if (mDailyPlanListAdapter.getFooterLayout() != null){
                mDailyPlanListAdapter.removeFooterView(noMoreData);
            }
        }else {
            if (mDailyPlanBeans.size() >= 4){
                if (mDailyPlanListAdapter.getFooterLayoutCount() == 0){
                    mDailyPlanListAdapter.addFooterView(noMoreData);
                }
            }
        }

    }

    @Override
    public void queryHistoryFailure(String err) {
        refreshLayout.finishRefresh();
        if (mDailyPlanListAdapter.getFooterLayoutCount() != 0){
            mDailyPlanListAdapter.removeFooterView(noMoreData);
        }
        setLoadingState(LoadingType.ERROR);
        UIUtils.showToast(err);
    }

    @Override
    public void onCalendarSelectOutOfRange(Calendar calendar) {

    }

    @Override
    public void onSelectOutOfRange(Calendar calendar, boolean isOutOfMinRange) {

    }

    @Override
    public void onCalendarRangeSelect(Calendar calendar, boolean isEnd) {
        // 进行筛选....
        for (int i=0;i<mSelectCalendars.size();i++){
            Calendar innerCalendar = mSelectCalendars.get(i);
            if (calendar.getDay() == innerCalendar.getDay() && calendar.getMonth() == innerCalendar.getMonth() &&
                 calendar.getYear() == innerCalendar.getYear()){
                calendarView.clearSelectRange();
                startTime = endTime = null;
                mPresenter.queryHistoryPlan(startTime,endTime);
                tvNext.setVisibility(View.GONE);
                rlMax.setVisibility(View.GONE);
                rlMin.setVisibility(View.GONE);
                mSelectCalendars.clear();
                return;
            }
        }
        mSelectCalendars.clear();
        if (!isEnd) {
            tvLeftMonth.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
            tvLeftYear.setText(String.valueOf(calendar.getYear()));
            tvLeftLunar.setText(calendar.getLunar());
            tvNext.setVisibility(View.GONE);
            rlMax.setVisibility(View.GONE);
            rlMin.setVisibility(View.VISIBLE);
            mSelectCalendars.add(calendar);
        } else {
            tvRightMonth.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
            tvRightYear.setText(String.valueOf(calendar.getYear()));
            tvRightLunar.setText(calendar.getLunar());
            tvNext.setVisibility(View.VISIBLE);
            rlMax.setVisibility(View.VISIBLE);
            rlMin.setVisibility(View.VISIBLE);
            mSelectCalendars.addAll(calendarView.getSelectCalendarRange());
        }

        if (!isEnd){
            // 只查询一天 时间开始和结束
            startTime  = calendar.getYear() + "-" + TimeUtil.fixTime(calendar.getMonth()) + "-" + TimeUtil.fixTime(calendar.getDay()) + " 00:00:00";
            endTime = calendar.getYear() + "-" + TimeUtil.fixTime(calendar.getMonth()) + "-" + TimeUtil.fixTime(calendar.getDay()) + " 23:59:59";
        }else {
            List<Calendar> calendars = calendarView.getSelectCalendarRange();
            // 如果只选择了一天

            if (calendars == null || calendars.size() == 0) {
                return;
            }
            Calendar calendar1 = calendars.get(0);
            Calendar calendar2 = calendars.get(calendars.size() - 1);
            startTime = calendar1.getYear() + "-" + TimeUtil.fixTime(calendar1.getMonth()) + "-" + TimeUtil.fixTime(calendar1.getDay()) + " 00:00:00";
            endTime = calendar2.getYear() + "-" + TimeUtil.fixTime(calendar2.getMonth()) + "-" + TimeUtil.fixTime(calendar2.getDay()) + " 23:59:59";
        }
        // 进行历史查询
        mPresenter.queryHistoryPlan(startTime,endTime);
    }

    /**
     * 设置当前日历的年月...
     * @param year
     * @param month
     */
    @Override
    public void onMonthChange(int year, int month) {
        tvCurrMonth.setText(year+"."+month);
    }
}
